<script type="text/javascript">
    // 点击相册事件(经查应该用事件委托对已经存在的父元素 委托事件)
    
    const leftdom = document.querySelector(".left");
    leftdom.addEventListener("click", function(event) {
        // <a></a> 被click
        if (event.target && event.target.nodeName.toUpperCase() === "A") {
            const adom = event.target;
            const name = adom.innerText;
            let pics = document.querySelectorAll(".pic");
            for (let pic of pics) {
                // console.log(name);
                // console.log("-------");
                // console.log(pic.dataset.name);
                if (pic.dataset.name === name) {
                    pic.classList.add("selected"); // display: none;
                } else {
                    pic.classList.remove("selected");
                }
            }
            
            // set the backgroundColor
            let adoms = leftdom.querySelectorAll("a");
            for (let x of adoms) {
                if (x === adom) {
                    x.style.backgroundColor = "#aaa";
                    x.style.borderRadius = "4px";
                }
                else {
                    x.style.backgroundColor = leftdom.style.backgroundColor;
                    x.style.borderRadius = "0";
                }
            }
        }
        
        // 删除相册<button></button> 被click
        if (event.target.nodeName.toUpperCase() === "BUTTON") {
            let buttondom = event.target;
            let name = buttondom.name;
            if (name === "默认相册") {
                return; 
            }

            // 删除这个相册索引
            let picCollectiondom = buttondom.parentNode;
            picCollectiondom.parentNode.removeChild(picCollectiondom);

            // 1.删除dataset.name = name 的div.pic 相册
            // 2.并且让上一个div.pic selected
            let picdoms = document.querySelectorAll("div.pic");
            for (let i = 0; i < picdoms.length; i++) {
                if (picdoms[i].dataset.name === name) {
                    picdoms[i].parentNode.removeChild(picdoms[i]);   
                    picdoms[i - 1].classList.add("selected");
                    break;
                }
            }
            // 服务器端删除 name 文件夹
            fetch("/delete-album/" + name, {
                method: "delete"
            }).then(res => {
                if (!res.json) {
                    console.log("The response body is actually null");
                }
            });
        }
    });
</script> 